//
//  CYMeHttpTool.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/30.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYMeHttpTool.h"
#import "CYURL.h"
#import "MBProgressHUD+MJ.h"
#import "CYLoginHttpTool.h"
#import "MJExtension.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "CYJsonInfo.h"
#import "CYCompanyUserTool.h"

@implementation CYMeHttpTool

+ (void)updateUserWithParams:(NSDictionary *)params success:(HttpRequestSuccess)success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL updateUserPath] params:params success:^(id json) {
        if (success) {
            success(json);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
            [MBProgressHUD showError:CYServerConnectFailure];
        }
    }];
}

+ (void)userWithParams:(NSDictionary *)params success:(void (^)(CYUser *user))success failure:(HttpRequestFailure)failure {
    
    [CYHttpTool postWithURL:[CYURL userPath] params:params success:^(id json) {
        if (success) {
            if ([json[@"success"] isEqualToString:@"fail"]) {
                NSError *error = [NSError errorWithDomain:@"jsonFailMsg" code:0 userInfo:@{@"message":json[@"message"]}];
                failure(error);
            }else {
                success([CYUser objectWithKeyValues:json]);
            }
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
}

+ (void)modifyPasswordWithParams:(NSDictionary *)params success:(void (^)(NSString *message))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL modifyPasswordPath] params:params success:^(id json) {
        CYLog(@"%@", json);
        if ([json[@"success"] isEqualToString:@"success"]) {
            if (success) {
                success(json[@"message"]);
            }
        }else {
            if (failure) {
                NSError *error = CYError(json[@"message"], CYErrorCodeErrorFromService);
                failure(error);
            }
        }
        
    } failure:^(NSError *error) {
        CYLog(@"修改密码服务器连接失败：%@", error);
    }];
}

+ (void)loanListWithParams:(NSDictionary *)params success:(void (^)(NSArray *arr))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL shared].loanList params:params success:^(id json) {
        NSParameterAssert(json);
        if (json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                if (success) {
                    success(jsonInfo.data);
                }
            } else {
                if (failure) {
//                    failure(CYError(jsonInfo.message, jsonInfo.errorCode.intValue));
                    CYLog(@"jsoninfo: %@ - %@", jsonInfo.message, jsonInfo.errorCode);
                }
            }
        } else {
            if (failure) {
//                failure(CYError(@"返回json为空", CYErrorCodeNOData));
                CYLog(@"返回json为空");
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"获取借款信息失败：%@", error);
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)payBackListWithParams:(NSDictionary *)params success:(void (^)(NSArray *arr))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL shared].payBackList params:params success:^(id json) {
        NSParameterAssert(json);
        if (json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                if (success) {
                    success(jsonInfo.data);
                }
            } else {
                if (failure) {
                    failure(jsonInfo.message);
                    CYLog(@"jsoninfo: %@", jsonInfo.message);
                }
            }
        } else {
            if (failure) {
//                failure(CYError(@"返回json为空", CYErrorCodeNOData));
                CYLog(@"返回json为空");
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"获取还款信息失败：%@", error);
    }];
}

+ (void)payBackDetailListWithParams:(NSDictionary *)params success:(void (^)(NSArray *arr))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL shared].payBackDetail params:params success:^(id json) {
        NSParameterAssert(json);
        if (json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                if (success) {
                    success(jsonInfo.data);
                }
            } else {
                if (failure) {
                    failure(jsonInfo.message);
                    CYLog(@"jsoninfo: %@", jsonInfo.message);
                }
            }
        } else {
            if (failure) {
//                failure(CYError(@"返回json为空", CYErrorCodeNOData));
                CYLog(@"返回json为空");
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"获取还款记录还款详情失败：%@", error);
    }];
}

/**
 *  获取提现额度
 *
 *  @param params
 *  @param success
 *  @param failure
 */
+ (void)getCreditCeilingWithParams:(NSDictionary *)params success:(void (^)(NSString *message))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL shared].getCreditCeiling params:params success:^(id json) {
        CYLog(@"获取提现额度: %@", json);
    } failure:^(NSError *error) {
        CYLog(@"获取提现额度: %@", error);
    }];
}

+ (void)getUserStatusForSuccess:(void (^)(CYUser *user))success failure:(HttpRequestFailure2)failure {
    CYUser *user = [CYLoginHttpTool userData].user;
    if (user) {
        [CYHttpTool postWithURL:[CYURL shared].getUserStatus params:@{@"userId": user.userId, @"token": user.token, @"type": @"0"} success:^(id json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isNoExamine) {
                if (success) {
//                    user.certificateExamineStatus = jsonInfo.data[@"examineStatus"];
//                    user.examineReason = jsonInfo.data[@"examineReason"];
                    [CYLoginHttpTool updateUserData:user];
                    success(user);
                }
            } else if (jsonInfo.isNoLogin) {
                if (failure) {
                    failure(kCYLoginStatusError, NO);
                }
            }
        } failure:^(NSError *error) {
            CYLog(@"获取用户审核状态错误:%@", error);
            if (failure) {
                failure(@"网络错误", YES);
            }
        }];
    } else {
        NSAssert(user, @"用户没有登陆");
        if (failure) {
            failure(nil, CYError(@"用户没有登陆", CYErrorCodeNoLogin));
        }
    }
}

+ (void)getCompanyUserStatusForSuccess:(void (^)(CYCompanyUserModel *user))success failure:(HttpRequestFailure1)failure {
    CYCompanyUserModel *user = [CYCompanyUserTool companyUser];
    if (user) {
        [CYHttpTool postWithURL:[CYURL shared].getUserStatus params:@{@"userId": user.carCompanyUserId, @"token": user.token, @"type": @(CYUserTypeCompany)} success:^(id json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isNoExamine) {
                user.examineStatus = jsonInfo.data[@"examineStatus"];
                user.examineReason = jsonInfo.data[@"examineReason"];
                [CYCompanyUserTool updateUserData:user];
                if (success) {
                    success(user);
                }
            } else if (jsonInfo.isNoLogin) {
                if (failure) {
                    failure(jsonInfo.success, nil);
                }
            } else if (jsonInfo.isSuccess) {
                user.examineStatus = CYStringFormat(@"%@", @(CYExamineStatusYES));
                [CYCompanyUserTool updateUserData:user];
                if (success) {
                    success(user);
                }
            }
        } failure:^(NSError *error) {
            CYLog(@"获取企业用户审核状态错误:%@", error);
            if (failure) {
                failure(nil, error);
            }
        }];
    } else {
        NSAssert(user, @"企业用户没有登陆");
        if (failure) {
            failure(nil, CYError(@"企业用户没有登陆", CYErrorCodeNoLogin));
        }
    }
}

/**
 *  从相册中选取图片
 *
 *  @param delegate
 *  @param completion 
 */
+ (void)imageFromPhotoLibraryWithController:(UIViewController *)con Delegate:(id<UIImagePickerControllerDelegate, UINavigationControllerDelegate>)delegate completion:(void (^)(void))completion {
    if ([self isPhotoLibraryAvailable]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = delegate;
        [con presentViewController:controller animated:YES completion:completion];
    }
}

+ (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary];
}

/**
 *  相机拍照选取图片
 *
 *  @param delegate
 *  @param completion
 */
+ (void)imageFromCameraWithController:(UIViewController *)con Delegate:(id<UIImagePickerControllerDelegate, UINavigationControllerDelegate>)delegate completion:(void (^)(void))completion {
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        }
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = delegate;
        [con presentViewController:controller animated:YES completion:completion];
    }
}

+ (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

+ (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

+ (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

+ (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}


    
+ (void)ShopwithaddressWithParams:(NSDictionary *)params success:(void (^)(NSString *message))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL ShopAddress] params:params success:^(id json) {
        CYLog(@"%@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success(jsonInfo.message);
            }
        }
//        if ([json[@"success"] isEqualToString:@"success"]) {
//            if (success) {
//                success(json[@"message"]);
//            }
//        }else {
//            if (failure) {
//                NSError *error = CYError(json[@"message"], CYErrorCodeErrorFromService);
//                failure(error);
//            }
//        }
        
    } failure:^(NSError *error) {
        CYLog(@"积分商城服务器连接失败：%@", error);
        if (failure) {
            failure(error);
        }
    }];
}


@end
